#include "ColorSelect.h"
#include "ui_ColorSelect.h"
#include <QBoxLayout>


ColorSelect::ColorSelect(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::ColorSelect),
	LedList(NULL)
{
	ui->setupUi(this);
	colorPicker = new QtColorTriangle(this);
	connect(colorPicker,SIGNAL(colorChanged(const QColor&)),this,SLOT(onColorChanged(const QColor&)));

	currLabel = new QLabel(this);
	currLabel->setAutoFillBackground(true);
	QIntValidator* valid = new QIntValidator(0,255,this);
	editR = new QLineEdit(this); editR->setValidator(valid);
	editG = new QLineEdit(this); editG->setValidator(valid);
	editB = new QLineEdit(this); editB->setValidator(valid);
	labelR = new QLabel("R");
	labelG = new QLabel("G");
	labelB = new QLabel("B");

	connect(editR,SIGNAL(editingFinished()),this,SLOT(onEditFinished()));
	connect(editG,SIGNAL(editingFinished()),this,SLOT(onEditFinished()));
	connect(editB,SIGNAL(editingFinished()),this,SLOT(onEditFinished()));

	QGridLayout* grid = new QGridLayout;
	grid->addWidget(labelR,0,0);
	grid->addWidget(labelG,1,0);
	grid->addWidget(labelB,2,0);
	grid->addWidget(editR,0,1);
	grid->addWidget(editG,1,1);
	grid->addWidget(editB,2,1);

	QVBoxLayout* layout1 = new QVBoxLayout;
	layout1->addWidget(currLabel,1);
	layout1->addLayout(grid,1);

	QHBoxLayout* layout2 = new QHBoxLayout(this);
	layout2->insertLayout(0,layout1,0);
	layout2->insertWidget(1,colorPicker,1);

	setLayout(layout2);

    //TimeEvent = new QTimer();
    //connect(TimeEvent,SIGNAL(timeout()),this,SLOT(onTimerr()));
    //TimeEvent->start(100);
}

ColorSelect::~ColorSelect()
{
	delete ui;
}

void ColorSelect::onColorChanged(const QColor &col)
{
	QPalette pal = currLabel->palette();
	pal.setColor(currLabel->backgroundRole(),col);
	currLabel->setPalette(pal);
	currLabel->update();

	editR->setText(QString("%1").arg(col.red()));
	editG->setText(QString("%1").arg(col.green()));
	editB->setText(QString("%1").arg(col.blue()));

	if(!LedList) return;
	QListIterator<Led*> it(*LedList);
	while (it.hasNext()) {
		it.next()->setColor(col);
	}
	emit colorChanged();
}

void ColorSelect::onEditFinished()
{
	QColor col;
	col.setRed(editR->text().toInt());
	col.setGreen(editG->text().toInt());
	col.setBlue(editB->text().toInt());

    colorPicker->setColor(col);
}

void ColorSelect::onTimerr(){
    QColor col = colorPicker->color();
    col.setHsv((col.hue()+3)%360,col.saturation(),col.value());
    colorPicker->setColor(col);
}
